<?php
/**
 * 万嘉关务 * 订单同步接口
 */
namespace ordersync;

use app\common\model\Area;
use request\Request;
use request\RequestException;

class WMSSyncRequest extends Request {

    protected $method = 'soap';
    protected $apiMethodName = 'AddImport';
    protected $importType = 1;

    public function __construct()
    {
        $url = rtrim(config('wms_api'), '/') . '/CrossBorderWebService/PreOrderService.asmx?WSDL';
        $this->setUrl($url);
    }

    /**
     * @return int
     */
    public function getImportType()
    {
        return $this->importType;
    }

    /**
     * @param int $importType
     */
    public function setImportType($importType)
    {
        $this->importType = $importType;
    }

    /**
     * 请求数据转化
     * @param $order
     * @param int $dimension // 数组维度
     * @return array
     * @throws RequestException
     */
    protected function requestTransfer($order, $dimension = 1) {
        $list = [];
        $tmp_amount = 0;
        $trade_mode = $order['trade_mode'];
        $total = 0;
        $goodsModel = model('goods');
        foreach($order['extend_order_goods'] as $key => $item) {
            if($item['goods_type'] == 5) continue;  // 赠品不上传
            $goods = $goodsModel->getGoodsInfo(['goods_id' => $item['goods_id']]);

            if(!$goods) continue;
            $goods_common = $goodsModel->getGoodsCommonInfoByID($goods['goods_commonid']);
            $list[] = [
                'GOODS_NAME'                    => $goods_common['goods_name'],
                'GOODS_SPECIFICATION'           => $goods_common['declare_spec'],           // 商品规格
                'PRODUCTION_MARKETING_COUNTRY'  => dict_convert('country_id_code', $goods['country']),          // 国家代码
                'DECLARE_PRICE'                 => $goods['declare_price'],       // 申报单价
                'DECLARE_COUNT'                 => $goods['declare_num'] * $item['goods_num'],         // 申报数量
                'DECLARE_MEASURE_UNIT'          => $goods['declare_unit'],        // 计量单位
                'GOODS_ROUGH_WEIGHT'            => $goods['gross_weight'] * $item['goods_num'],   // 毛重
                'CREATE_TIME' => '',                            // 创建时间
                'PRODUCT_RECORD_NO' => config('wms_config.PRODUCT_RECORD_NO'), // 总局商品备案号
                'WEBSITE_HREF' => url('home/goods/index', ['goods_id' => $goods['goods_id']], true, true),     //  网站链接
                'MAIL_TAX_NO' => '',                            // 行邮税号
                'HS_CODE' => $goods['hs_code'],                 // HS 编码
                'SEQ_NO' => $key + 1 ,//商品序号
                'SKU' => $goods['goods_serial'] ?: $goods['goods_commonid'],//企业商品货号
                'ITEM_DESCRIBE' => '',//企业商品描述
                'PROD_BRD_CN' => '',//品牌
                'PRICE_TOTAL_VAL' => $goods['declare_price'] * $goods['declare_num'] * $item['goods_num'],//总价
                'COMM_BARCODE' => $goods['goods_serial'] ?: $goods['goods_commonid'],//商品条码
                'REMARK' => '',//备注
            ];
            $tax = $goods['tax_rate']/100 * $goods['declare_price'] * $goods['declare_num'] * $item['goods_num'];
            $total += $tax;
            $tmp_amount += $goods['declare_num'] * $item['goods_num'];
        }

        if($trade_mode == TRADE_NORMAL){
            throw new RequestException('订单类型错误');
        }

        $trade_mode = config('trade_mode_code.'.$trade_mode);
        //总件数
        $declare_num_total = $tmp_amount;
        //行政编码
        $area_code = Area::getProvinceCodeByCityId($order['extend_order_common']['reciver_city_id']);
        $head = [
            'APP_TYPE' => $this->getImportType(),       // 报送类型
            'I_E_FLAG' => 'I',       // 进出口标志
            'BILL_TYPE' => $trade_mode,      // 贸易方式
            'ORDER_TOTAL_AMOUNT' => 1,      // 订单总数
            'ORDER_NO' => $order['order_sn'],
            'COMPANY_NAME' => config('wms_config.COMPANY_NAME'),   // 电商平台备案名称
            'COMPANY_CODE' => config('wms_config.COMPANY_CODE'),   // 备案编码
            'EBC_NAME' => config('wms_config.EBC_NAME'),       // 电商企业备案名称
            'EBC_CODE' => config('wms_config.EBC_CODE'),       // 电商企业备案编码
            'TRADE_TIME' => date('Y-m-d H:i:s', $order['payment_time']),    // 成交时间
            'CURR_CODE' => 142,                                       // 成交币制 (默认 人民币)
            'CONSIGNEE_EMAIL' => $order['buyer_email'],               // 收货人 email
            'CONSIGNEE_TEL' => $order['extend_order_common']['reciver_info']['mob_phone'],  // 联系方式
            'CONSIGNEE' => $order['extend_order_common']['reciver_name'],                   // 收件人姓名
            'CONSIGNEE_ADDRESS' => $order['extend_order_common']['reciver_info']['address'],// 收件地址
            'TOTAL_COUNT' => $declare_num_total,        // 总件数
            'POST_MODE' => '',                          // 发货方式
            'SALER_COUNTRY' => '',                      // 发件人国家
            'ADDRESSOR_NAME' => '',                     // 发件人姓名
            'CREATE_TIME' => '',                        // 创建日期
            'LOGIS_COMPANY_NAME' => config('wms_config.LOGIS_COMPANY_NAME'),   // 物流企业名称
            'LOGIS_COMPANY_CODE' => config('wms_config.LOGIS_COMPANY_CODE'),   // 物流企业编号
            'GOODS_DECLAR_CHECK_ID' => '',              // 包裹物理主键id
            'DISCOUNT' => $order['extend_order_common']['voucher_price'],  // 优惠减免金额
            'TAX_TOTAL' => $total,                      // 订单商品税款
            'ACTURAL_PAID' => $order['order_amount'],   // 实际支付金额
            'BUYER_REG_NO' => $order['buyer_id'],       // 订购人注册号
            'BUYER_NAME' => $order['extend_order_common']['reciver_name'],  // 订购人姓名
            'BUYER_ID_TYPE' => 1,                       // 订购人证件类型
            'BUYER_ID_NUMBER' =>  $order['extend_order_common']['reciver_info']['id_card_no'],  // 订购人证件号码
            'BATCH_NUMBER' => '',                       // 商品批次号
            'CONSIGNEE_DITRIC' => $area_code,           // 收货人行政区划代码
            'SENDER_CITY' => '',                        // 发件人城市
            'BUYER_ID_TEL' => $order['extend_order_common']['reciver_info']['mob_phone'],   // 订购人电话
            'PRICE_TOTAL_VAL' => $order['goods_amount'],// 订单商品货款
            'FREIGHT' => $order['shipping_fee'],        // 订单商品运费
            'LOGISTICS_NO' => $order['shipping_code'],  // 物流运单号
            'MAIN_WB_NO' => '',                         // 总运单号
            'INSURED_FEE' => '0',                        // 保价金额
            'PreOrderLists' => $list,
        ];
        return [
            'orderBill' => str_replace([
                '<PreOrderLists>',
                '</PreOrderLists>',
                '<node>',
                '</node>',
            ], [
                '',
                '',
                '<PreOrderLists>',
                '</PreOrderLists>',
            ], $this->arrayToXml($head, null, null, 'PreOrderHead')),    // 调整XML格式
            'token' => OrderSync::WMSToken(),
        ];
    }

    /**
     * 验证接口返回数据
     * @param $response
     * @throws RequestException
     */
    protected function checkResponse($response)
    {
        if($response['Status'] == 0) {
            throw new RequestException($response['Remark']);
        }
    }

    /**
     * 获取响应数据
     * @return mixed
     */
    public function getResponse()
    {
        return $this->response['ID'];
    }

    /**
     * @param mixed $response
     * @throws \request\RequestException
     */
    public function setResponse($response)
    {
        $objectXml = simplexml_load_string($response);//将文件转换成 对象
        $xmlJson = json_encode($objectXml);//将对象转换个JSON
        $this->response = json_decode($xmlJson,true);//将json转换成数组

        $this->checkResponse($this->response);
    }
}